package com.hps.springboot.controller;

import com.hps.springboot.model.Girl;
import com.hps.springboot.pojo.ResponseBody;
import com.hps.springboot.repository.GirlRepository;
import com.hps.springboot.service.GirlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    @RequestMapping("/girls")
    public List<Girl> girlList() {
        return girlRepository.findAll();
    }

    @RequestMapping("/girlsAdd")
    public ResponseBody<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) {
        ResponseBody<Girl> responseBody = new ResponseBody<>();
        if(bindingResult.hasErrors()) {
            responseBody.setCode(1);
            responseBody.setMsg(bindingResult.getFieldError().getDefaultMessage());
            return responseBody;
        }
        Girl g = girlRepository.save(girl);
        responseBody.setCode(0);
        responseBody.setMsg("msg");
        responseBody.setData(g);
        return responseBody;
    }

    @RequestMapping("/girlsQuery/{id}")
    public Girl girlQuery(@PathVariable("id") Integer id) {
        return girlRepository.findOne(id);
    }

    @RequestMapping("/girlsUpdate/{id}")
    public Girl GirlUpdate(@PathVariable("id") Integer id,
                             String cupSize,
                             Integer age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setAge(age);
        girl.setCupSize(cupSize);
        return girlRepository.save(girl);
    }

    @RequestMapping("/girlsDelete/{id}")
    public void girlDelete(@PathVariable("id") Integer id) {
        girlRepository.delete(id);
    }

    @RequestMapping("/queryByAge/{age}")
    public List<Girl> queryByAge(@PathVariable("age") Integer age) {
        return girlRepository.findByAge(age);
    }

    @RequestMapping("/girls/two")
    public void insertTwo() {
        girlService.insertTwo();
    }

    @RequestMapping("/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        girlService.getAge(id);
    }
}
